const http = require('http');
const fs = require('fs');
const querystring = require('querystring');
const urlLib = require('url');

let users = {};

const server = http.createServer((req, res) => {

    let str = '';
    req.on('data', (data) => {
        str += data;
    });

    req.on('end', () => {
        let obj = urlLib.parse(req.url, true);

        const url = obj.pathname;
        const GET = obj.query;
        const POST = querystring.parse(str);

        //  区分接口文件
        if (url === '/user') {
            switch(GET.act) {
                case 'reg':
                    if (users[GET.user]) {
                        res.write('{"ok": false, "msg": "此帐号已经存在了！"}');
                    } else {
                        users[GET.user] = GET.pass;
                        res.write('{"ok": true, "msg": "注册成功!"}');
                    }
                    break;
                case 'login':
                    if (!users[GET.user]) {
                        res.write('{"ok": false, "msg": "次帐号不存在!"}');
                    } else if (users[GET.user] !== GET.pass) {
                        res.write('{"ok": false, "msg": "您输入的帐号或者密码错误"}');
                    } else {
                        res.write('{"ok": true, "msg": "登录成功牛逼"}');
                    }
                    break;
                default:
                    res.write('{"ok": false, "msg": "未知错误"}');
                    break;
            }
            res.end();
        } else {

            /**
             * 直接读取文件
            */
            const file_name = `./www${url}`;
            fs.readFile(file_name, (err, data) => {
                if (err) {
                    res.write('404 找不到页面!');
                } else {
                    res.write(data);
                }

                res.end();
            });
        }
    });
});

server.listen(8080, () => {
    console.log('访问成功!');
});